package com.znf.biz.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znf.base.PageRespDto;
import com.znf.base.exception.BizException;
import com.znf.biz.system.converter.SysUserConverter;
import com.znf.biz.system.dto.sys.req.*;
import com.znf.biz.system.dto.sys.resp.SysUserRespDto;
import com.znf.biz.system.entity.SysUser;
import com.znf.biz.system.mapper.SysUserMapper;
import com.znf.biz.system.service.ISysUserService;
import com.znf.config.CustomUserDetails;
import com.znf.util.CurrentUserUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author Xiewm
 * @since 2024-11-06
 */
@Slf4j
@Data
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final SysUserConverter sysUserConverter;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public PageRespDto<SysUserRespDto> page(SysUserPageReqDto param) {
        long pageNum = param.getPageNum();
        long pageSize = param.getPageSize();
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SysUser::getNickName, param.getLikeNickName())
                .eq(SysUser::getStatus, "0")
                .eq(SysUser::getUserName, param.getUserName());
        Page<SysUser> data = page(page, queryWrapper);

        PageRespDto<SysUserRespDto> result = new PageRespDto<>();
        result.setTotal(data.getTotal());
        result.setRecords(sysUserConverter.sysUserToSysUserRespDto(data.getRecords()));
        return result;
    }

    @Override
    public SysUserRespDto get(Long userId) {
        SysUser one = lambdaQuery().eq(SysUser::getUserId, userId).one();
        return sysUserConverter.sysUserToSysUserRespDto(one);
    }

    @Override
    public SysUser findByUsername(String username) {
        return lambdaQuery().eq(SysUser::getUserName, username).one();
    }

    @Override
    public boolean add(SysUserAddReqDto param) {
        CustomUserDetails currentUser = CurrentUserUtil.getCurrentUser();
        Long userId = currentUser.getUserId();
        SysUser sysUser = sysUserConverter.sysUserAddReqDtoToSysUser(param);
        sysUser.setPassword(passwordEncoder.encode(param.getPassword()));
        sysUser.setCreateTime(LocalDateTime.now());
        return save(sysUser);
    }

    @Override
    public boolean modify(SysUserModifyReqDto param) {
        SysUser user = sysUserConverter.sysUserModifyReqDtoToSysUser(param);
        updateById(user);
        return true;
    }

    @Override
    public boolean changePwd(ChangePwdReqDto param) {
        CustomUserDetails currentUser = CurrentUserUtil.getCurrentUser();
        SysUser user = findByUsername(currentUser.getUsername());
        if (passwordEncoder.matches(param.getOldPwd(), user.getPassword())) {
            String encodePwd = passwordEncoder.encode(param.getNewPwd());
            lambdaUpdate().set(SysUser::getPassword, encodePwd)
                    .set(SysUser::getUpdateBy, currentUser.getUsername())
                    .set(SysUser::getUpdateTime, LocalDateTime.now())
                    .eq(SysUser::getUserId, user.getUserId()).update();
            return true;
        } else {
            throw new BizException("密码错误请重新输入");
        }

    }

    @Override
    public boolean resetPwd(ResetPwdReqDto param) {
        SysUser user = lambdaQuery().eq(SysUser::getUserId, param.getUserId()).one();
        if (user == null) {
            throw new BizException("用户不存在");
        }
        String encodePwd = passwordEncoder.encode(param.getPassword());
        lambdaUpdate().set(SysUser::getPassword, encodePwd)
                .eq(SysUser::getUserId, param.getUserId()).update();
        return true;
    }


}
